package com.ds.dsfans.shell.util.adb.device;

import com.ds.dsfans.shell.util.common.ShellUtil;

import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;


public class Devices {

    private static Map<String, Device> devices;

    /**
     * 执行adb命令
     *
     * @param adb
     * @return
     */
    public static String Shell(String adb) {
        Process cmd = ShellUtil.adbCmd(adb);
        String shellOut = ShellUtil.getShellOut(cmd);
        return shellOut;
    }

    /**
     * 初始化
     */
    public static void init() {
        devices = new LinkedHashMap<>();
        String devicesStr = Shell("devices");
        String[] ids = devicesStr.split("\r\n");
        for (int i = 1; i < ids.length; i++) {
            String[] split = ids[i].split("\t");
            if (split.length > 1 && split[1].equals("device")) {
                String id = split[0];
                Device device = Device.getDevice(id);
                devices.put(id, device);
            }
        }
    }

    /*
     * @Description: 根据设备id获取device对象
     * @return
     **/
    public static Device getDevice(String deviceId) {
        init();
        Device device = devices.get(deviceId);
        return device;
    }

    /**
     * 获取所有设备
     *
     * @return
     */
    public static List<Device> getDevices() {
        init();
        ArrayList<Device> ds = new ArrayList<>();
        devices.entrySet().stream().forEach(item -> {
            ds.add(item.getValue());
        });
        return ds;
    }

    /*
     * @Description: 获取连接设备数
     **/
    public static int getDevicesNum() {
        init();
        int size = devices.size();
        return size;
    }


}
